<template>
  <div class="page-container 123">
    <!-- 读取配置中 -->
    <template v-if="!userStore.epServiceTypes">
      <a-spin dot />
    </template>
    <template v-else>
      <!-- 暂未配置 -->
      <template v-if="userStore.epServiceTypes?.length == 0">
        <div class="no-config">
          <SvgIcon name="no-config" style="width: 100%; height: 100%" />
          <p>当前商户未配置服务类型，请选择本商户支持服务类型</p>
        </div>
      </template>
      <template v-else>
        <a-tabs v-model:active-key="activeTabsKey" @change="tabsChangeFn">
          <!-- 配置了短长租业务才显示对应的长短租选项 -->
          <a-tab-pane :key="1" title="自驾短租" v-if="userStore.epServiceTypes.includes(1)" />
          <a-tab-pane :key="2" title="自驾长租" v-if="userStore.epServiceTypes.includes(2)" />
        </a-tabs>
        <div class="price-config-wrapper">
          <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="fetchData" />
          <!-- 短租配置 -->
          <shortOrderConfig
            ref="shortOrderConfigRef"
            @viewSiteList="viewSiteListFn"
            @editTemplate="editTemplateFn"
            @addTemplate="addTemplateFn"
            @toggleStatus="toggleStatusFn"
            v-if="activeTabsKey == 1"
          />
          <!-- 长租配置 -->
          <longOrderConfig
            ref="longOrderConfigRef"
            @viewSiteList="viewSiteListFn"
            @editTemplate="editTemplateFn"
            @addTemplate="addTemplateFn"
            @toggleStatus="toggleStatusFn"
            v-if="activeTabsKey == 2"
          />
        </div>
      </template>
    </template>
    <!-- 模板门店弹窗 -->
    <template-site-modal ref="templateSiteModalRef" />
  </div>
</template>

<script setup name="CarModelPriceList">
  import { ref, reactive, computed, watch, provide, nextTick, onMounted, onUnmounted } from 'vue'
  import { setTemplateEnabled, getTemplateSiteList } from '@/api/business/price.js'
  import shortOrderConfig from './components/short-order-config.vue'
  import longOrderConfig from './components/long-order-config.vue'
  import templateSiteModal from './components/template-site-modal.vue'
  import { usePageDict } from '@/hooks/useDict'
  import { Modal, Message } from '@arco-design/web-vue'
  import useNavigate from '@/hooks/useNavigate'
  import bus from '@/utils/bus'
  const { registerListHotUpdate, navigateTo, navigateToCreate } = useNavigate()

  // 读取商户配置开始
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()
  userStore.setEpDetail(() => {
    const epServiceTypes = userStore.epServiceTypes
    if (epServiceTypes.length == 1) {
      activeTabsKey.value = epServiceTypes[0]
    } else {
      if (epServiceTypes.includes(1)) {
        activeTabsKey.value = 1
      } else if (epServiceTypes.includes(2)) {
        activeTabsKey.value = 2
      }
    }
    // 初始化查询
    queryParam.templateSort = activeTabsKey.value.toString()
    fetchData(1)
  })
  // 读取商户配置结束
  const activeTabsKey = ref()
  // 切换 tabs
  const tabsChangeFn = (val) => {
    queryParam.templateSort = val
    fetchData(1)
  }
  // 页面初始化 开始
  watch(
    () => userStore.epServiceTypes,
    (newVal, oldVal = []) => {
      if (newVal && newVal.toString() != oldVal.toString()) {
        if (!newVal.find((item) => item == activeTabsKey.value)) {
          const initServiceType = newVal[0]
          activeTabsKey.value = initServiceType.toString()
          queryParam.templateSort = activeTabsKey.value
          fetchData(1)
        }
      }
    }
  )
  // 页面初始化 结束

  // 接口参数（不包含page信息）
  const queryParam = reactive({})
  provide('queryParam', queryParam)

  // 查询条件
  const dict = usePageDict('tenantPriceDict')
  provide('dict', dict)

  const searchList = computed(() => {
    return [
      { label: '模板名称', prop: 'templateNameLike', type: 'a-input' },
      {
        label: '应用门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_lease_list',
        },
      },
      {
        label: '模板状态',
        prop: 'status',
        type: 'a-select',
        options: dict.statusMap,
      },
      { label: '车型名称', prop: 'modelIdList', type: 'remote-select', attrs: { type: 'car_model_tenantList_multiple' } },
    ]
  })

  // 查询数据
  const shortOrderConfigRef = ref(null)
  const longOrderConfigRef = ref(null)
  const fetchData = (pageNumber) => {
    nextTick(() => {
      shortOrderConfigRef.value && shortOrderConfigRef.value.loadData(pageNumber)
      longOrderConfigRef.value && longOrderConfigRef.value.loadData(pageNumber)
    })
  }

  // 查看门店列表弹窗
  const templateSiteModalRef = ref()
  const viewSiteListFn = (record) => {
    templateSiteModalRef.value.open(record, getTemplateSiteList)
  }

  // 添加模板
  const addTemplateFn = () => {
    const templateSort = queryParam.templateSort
    // 增加count的目的是为了保证新增页面的路由地址不同，否则会缓存
    navigateToCreate(
      `/car-model-price/create/${templateSort}?count=${createTemplateCount.value}`,
      `新增${templateSort == 1 ? '短租' : '长租'}价格模板`
    )
  }
  // 编辑模板
  const editTemplateFn = (record) => {
    const templateSort = queryParam.templateSort
    navigateTo(
      `/car-model-price/edit/${record.id}?templateType=${record.templateType}&templateSort=${templateSort}`,
      `${record.templateName}-编辑`
    )
  }
  // 模板启用停用
  const toggleStatusFn = (record, operateName) => {
    new Promise((resolve) => {
      if (operateName == '启用') {
        resolve()
      } else {
        // 停用需要加二次确认
        Modal.confirm({
          title: '提示',
          simple: true,
          cancelText: '取消',
          okText: '确认',
          content: `请确认，是否停用？`,
          onBeforeOk: (done) => {
            resolve(done)
          },
        })
      }
    }).then((done) => {
      const param = {
        id: record.id,
        status: operateName == '启用' ? 1 : 0,
      }
      setTemplateEnabled(param)
        .then(() => {
          Message.success(`${operateName}成功`)
          // 手动更改状态
          fetchData()

          if (done) done(true)
        })
        .catch(() => {
          if (done) done(false)
        })
    })
  }

  const createTemplateCount = ref(1)
  onMounted(() => {
    // 注册热更新
    registerListHotUpdate(fetchData)
    bus.on('priceCarModelCreateSuccess', () => {
      createTemplateCount.value += 1
    })
  })
  onUnmounted(() => {
    bus.off('priceCarModelCreateSuccess')
  })
</script>

<style lang="less" scoped>
  .status-wrapper {
    height: 28px;
    .status-icon {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
      &.open {
        background: #00b42a;
      }
      &.close {
        background: #ea0000;
      }
    }
  }
  .no-config {
    width: 235px;
    height: 154px;
    padding-bottom: 40px;
    position: absolute;
    left: 50%;
    top: 20vh;
    margin-left: -117px;
    p {
      padding-top: 20px;
      text-align: center;
      font-size: 16px;
      color: #cad0dd;
    }
  }

  .site-num-wrapper {
    font-size: 14px;
    .site-num-val {
      vertical-align: middle;
      line-height: 20px;
    }
    .view-btn {
      border-radius: 2px;
      opacity: 1;
      border: 1px solid #1890ff;
      color: #1890ff;
      margin-left: 6px;
      height: 18px;
      line-height: 18px;
      padding: 0 8px;
      font-size: 12px;
      vertical-align: middle;
    }
  }
</style>
